document.getElementById('access_list').style.display = 'none';
document.getElementById('parameter_list').style.display = 'none';
document.getElementById('condition_list').style.display = 'none';
document.getElementById('value_list').style.display = 'none';
document.getElementById('search').style.display = 'none';
document.getElementById('fake').style.display = 'none';
sessionStorage.setItem("value",-1);
setfake();

$( document ).ready(function() {
    updateCitiesDropdown();

       
        // mostrar navigation bar
        document.getElementById('esconde').style.display = 'none';
        document.getElementById('esconde_tabelas').style.display = 'block';

        document.getElementById('cpe-info').style.display = 'block';
        //document.getElementById('cpe-alerts').style.display = 'block';
        

        //document.getElementById('cpe-info').style.display = 'none';
      //  $('#cpe-info div').html("<br><div class='alert alert-warning' role='alert'> Please Select a CPE ... </div>");
        //document.getElementById('cpe-alerts').style.display = 'none';

});

//Joao Rodrigues - Search CPE
function searchResult(el)
{
    var text_input_value = $("#" + el + "")[0].value;

    switch(el) {
        case "searchByZip":
            searchByZip(text_input_value)
            break;
        case "searchByMac":
            searchByMac(text_input_value)
            break;
        default:
            alert("Error: Case error searchBy");
    }
}

//Joao Rodrigues - Search CPE
function searchByZip(zip){

    var request = $.ajax({
            type:"POST",
            url:"webservs/get_data.php",
            data: {
                method: "get_cpe_info_by_zip",
                zip_code: zip
            },
            dataType: "json",
            error: function (xhr, status, error) {  alert ("erro: " + xhr.responseText); }
    });

    request.done( function (data){                    
        mostrar_graficos(data.cpe_id, data.mac, data.ssid);
    });
}

//Joao Rodrigues - Search CPE
function searchByMac(mac){

    var request = $.ajax({
            type:"POST",
            url:"webservs/get_data.php",
            data: {
                method: "get_cpe_info_by_mac",
                mac_address: mac
            },
            dataType: "json",
            error: function (xhr, status, error) {  alert ("erro: " + xhr.responseText); }
    });

    request.done( function (data){                    
        mostrar_graficos(data.cpe_id, data.mac, data.ssid);
    });

}  

/*
$("#list_cities_dropdown").click(function(){

});
*/

function updateCitiesDropdown(){
    var list_cities_dropdown = $('#list_cities_dropdown');
    list_cities_dropdown.empty();
    $("#list_access_dropdown").empty();
    list_cities_dropdown.append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=updateAccessDropdown('Portugal');>Portugal</a></li>");
    var request = $.ajax({
        type:"POST",
        url:"webservs/get_data.php",
        data: {
            method: "get_all_cities"
        },
        dataType: "json",
        error: function (xhr, status, error) {  alert ("erro updatecitiesdropdown: " + xhr.responseText); }
    });

    request.done( function (data){
       // console.log(data);
        $.each(data, function(i, city){
            list_cities_dropdown.append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=updateAccessDropdown('" + city + "');>"+city+"</a></li>");            
        });
    });
};

function updateAccessDropdown(city_name){
    $("#dropdownMenu1 > span").html("<span>" + city_name +" <span class='caret'></span></span>" ); //Mostra o texto escolhido na dropdown das cidades.
    $("#list_access_dropdown").empty();
    document.getElementById('access_list').style.display = 'block';
    sessionStorage.setItem("city",city_name);

    if(city_name=="Portugal")  {
    	$("#list_access_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=updateParameterDropdown('All');>All</a></li>");
    	$("#list_access_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=updateParameterDropdown('ADSL');>ADSL</a></li>");
    	$("#list_access_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=updateParameterDropdown('Fibra');>Fibra</a></li>");
    }
    else{
    	$("#list_access_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=updateParameterDropdown('All');>All</a></li>");
	    var request = $.ajax({
	        type:"POST",
	        url:"webservs/get_data.php",
	        data: {
	            method: "get_access_by_city",
	            city: city_name
	        },
	        dataType: "json",
	        error: function (xhr, status, error) {  alert ("erro updatestreetsdropdown: " + xhr.responseText); }
	    });

	    request.done( function (data){
	        console.log(data);
	        $.each(data, function(i, access){
	        	//var access_name_encoded = window.btoa(access[0]);
	        	//console.log(access);
	            //var street_name_encoded = window.btoa(street[0]); //Encode base64 - para prevenir illegal token
	            //street[0] = nome da rua, street[1] = zip
	            $("#list_access_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=updateParameterDropdown('" + access[0] + "');>"+access[0]+"</a></li>");
	            //$("#list_ruas_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=temp('" + street[1] + "');>"+street[0]+"</a></li>");
	        });
	    });
	}
};

function updateParameterDropdown(access_name){
    $("#dropdownMenu2 > span").html("<span>" + access_name +" <span class='caret'></span></span>" ); //Mostra o texto escolhido na dropdown das cidades.
    $("#list_parameter_dropdown").empty();
    document.getElementById('parameter_list').style.display = 'block';
    sessionStorage.setItem("access",access_name);

    var param = ["Wifi Quality", "Market Share", "Market Churn"];

    	for(var i=0; i<param.length;i++){
    		var param_encoded = window.btoa(param[i]);
    		$("#list_parameter_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=updateConditionDropdown('" + param_encoded + "');>"+param[i]+"</a></li>");
    	}

};

function updateConditionDropdown(param){
	 var param_decoded =  window.atob(param);
	 sessionStorage.setItem("parameter",param_decoded);
    $("#dropdownMenu3 > span").html("<span>" + param_decoded +" <span class='caret'></span></span>" ); //Mostra o texto escolhido na dropdown das cidades.
    $("#list_condition_dropdown").empty();
    $("#dropdownMenu5 > span").html("<span>Values <span class='caret'></span></span>" );
    $("#list_condition_dropdown").empty();
    $("#dropdownMenu4 > span").html("<span>Condition <span class='caret'></span></span>" );
    $("#list_value_dropdown").empty();
    document.getElementById('condition_list').style.display = 'block';
    document.getElementById('search').style.display = 'none';
    var conditions = ["Equal or Less", "Equal", "Equal or Greater"];
    sessionStorage.setItem("value",-1);
    	for(var i=0; i<conditions.length;i++){
    		var conditions_encoded = window.btoa(conditions[i]);
    		$("#list_condition_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=updateValueDropdown('" + conditions_encoded + "');>"+conditions[i]+"</a></li>");
    	}

};

function updateValueDropdown(param){
	 var param_decoded =  window.atob(param);
    $("#dropdownMenu4 > span").html("<span>" + param_decoded +" <span class='caret'></span></span>" ); //Mostra o texto escolhido na dropdown das cidades.
    $("#list_value_dropdown").empty();
    document.getElementById('value_list').style.display = 'block';
    parameter = sessionStorage.getItem("parameter");
    sessionStorage.setItem("condition",param_decoded);

    var quality = ["Idle", "Normal", "Strong", "Heavy" , "Extreme Heavy"];
    var percentages = ["0","10","20","30","40","50","60","70","80","90","100"];

    if (parameter=="Wifi Quality") {
    	for(var i=0; i<quality.length;i++){
    		$("#list_value_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=analysis('"+window.btoa(quality[i])+"');>"+quality[i]+"</a></li>");
    	}
    }
    else{
    	for(var i=0; i<percentages.length;i++){
    		$("#list_value_dropdown").append("<li role='presentation'><a role='menuitem' tabindex='-1' onclick=analysis('"+percentages[i]+"');>"+percentages[i]+" %</a></li>");
    	}
    }

};

function setfake(){
    var checkedValue = $('.fake:checked').val();
    if(checkedValue == "on") sessionStorage.setItem("fake" , "fake");
    else sessionStorage.setItem("fake" , "real");
    if (sessionStorage.getItem("value") != -1 && sessionStorage.getItem("value") != undefined ) search();
}

function analysis(value){
	if (isNaN(value)) 	sessionStorage.setItem("value",atob(value));
	else 				sessionStorage.setItem("value",value);
	var city = sessionStorage.getItem("city");
	var access = sessionStorage.getItem("access");
	var parameter = sessionStorage.getItem("parameter");
	var condition = sessionStorage.getItem("condition");
	var value = sessionStorage.getItem("value");

	if(condition == "Equal or Less") 		condition = "<=";
	if(condition == "Equal") 				condition = "=";
	if(condition == "Equal or Greater")		condition = ">=";

	if(parameter=="Wifi Quality"){
		$("#dropdownMenu5 > span").html("<span>" + value +" <span class='caret'></span></span>" ); //Mostra o texto escolhido na dropdown
	}
	if(parameter=="Market Churn"){
		$("#dropdownMenu5 > span").html("<span>" + value +" %<span class='caret'></span></span>" ); //Mostra o texto escolhido na dropdown
	}
	if(parameter=="Market Share"){
		$("#dropdownMenu5 > span").html("<span>" + value +" %<span class='caret'></span></span>" ); //Mostra o texto escolhido na dropdown
	}
	//alert("SELECT cpe_id FROM cpe WHERE city="+city+" AND access="+access+" AND " + parameter + " " + condition + " " + value);
    document.getElementById('search').style.display = 'block';
}

function search(){

    var city = sessionStorage.getItem("city");
    var access = sessionStorage.getItem("access");
    var parameter = sessionStorage.getItem("parameter");
    var condition = sessionStorage.getItem("condition");
    var value = sessionStorage.getItem("value");
    var fake = sessionStorage.getItem("fake");
    //alert("entrou") ;
    if(condition == "Equal or Less")        condition = "<=";
    if(condition == "Equal")                condition = "=";
    if(condition == "Equal or Greater")     condition = ">=";

    if(parameter=="Wifi Quality"){
        var method = "Quality";
        $.get( "elements/smart_analysis/smart.php?method="+method+"&city="+city+"&access="+access+"&parameter="+parameter+"&condition="+condition+"&value="+value+"&fake="+fake, function( data) {
            document.getElementById("cpe_table").innerHTML = data;
        });
    }
    if(parameter=="Market Churn"){
        var method = "Churn";
        $.get( "elements/smart_analysis/smart.php?method="+method+"&city="+city+"&access="+access+"&parameter="+parameter+"&condition="+condition+"&value="+value+"&fake="+fake, function( data) {
            document.getElementById("cpe_table").innerHTML = data;
        });
    }
    if(parameter=="Market Share"){
        var method = "Share";
        $.get( "elements/smart_analysis/smart.php?method="+method+"&city="+city+"&access="+access+"&parameter="+parameter+"&condition="+condition+"&value="+value+"&fake="+fake, function( data) {
            document.getElementById("cpe_table").innerHTML = data;
        });
    }
    //alert("SELECT cpe_id FROM cpe WHERE city="+city+" AND access="+access+" AND " + parameter + " " + condition + " " + value);

}

function selectcpe(cpe_id){
	sessionStorage.setItem("cpe_id", cpe_id);
	var request = $.ajax({
            type:"POST",
            url:"webservs/get_data.php",
            data: {
                method: "get_cpe_full_info",
                cpe_id: cpe_id
            },
            dataType: "json",
            error: function (xhr, status, error) {  alert ("errogetcpefullinfo: " + xhr.responseText); }
    });

    request.done( function (data){
        //definicao de localstorage dos restantes minutos
        sessionStorage.setItem("cpe_mac",                 data.mac);
        sessionStorage.setItem("cpe_ssid",                data.ssid);
        sessionStorage.setItem("cpe_zip",                 data.zip);
        sessionStorage.setItem("cpe_street",              data.street);
        sessionStorage.setItem("cpe_city",                data.city);
        sessionStorage.setItem("cpe_wlan_channel",        data.wlan_channel);
        sessionStorage.setItem("cpe_wlan_status",         data.wlan_status);
        sessionStorage.setItem("cpe_wlan_enable",         data.wlan_enable);
        sessionStorage.setItem("cpe_wlan_radioenable",    data.wlan_radioenable);
        sessionStorage.setItem("cpe_wlan_standard", "802.11 " + data.wlan_standard);
        sessionStorage.setItem("cpe_wlan_channelmode",    data.wlan_channelmode);
        sessionStorage.setItem("cpe_wlan_ssidadvert",     data.wlan_ssidadvert);
		sessionStorage.setItem("cpe_access",     	  data.access);
        //location.reload() //Reload da Pagina
	window.location="index.php";
    });
}